<template>
  <view class="flow-record-container">
    <!-- 顶部当前沐浴露余额 -->
    <view class="balance-header">
      <text class="balance-label">当前沐浴露：</text>
      <text class="balance-amount">{{ currentBalance.toFixed(2) }}包</text>
    </view>

    <!-- 时间筛选（无背景） -->
    <view class="time-filter">
      <view class="filter-dropdown" @tap="showTimePicker">
        <text class="filter-text">{{ selectedTime }}</text>
        <uni-icons type="down" size="16" color="#666666"></uni-icons>
      </view>
    </view>

    <!-- 流水记录列表 -->
    <view class="record-list">
      <!-- 加载状态 -->
      <view v-if="loading && page === 1" class="loading-wrapper">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view
        v-else-if="recordList.length === 0 && !loading"
        class="empty-wrapper"
      >
        <text class="empty-text">暂无记录</text>
      </view>

      <!-- 记录列表 -->
      <view
        v-else
        class="record-item-card"
        v-for="(item, index) in recordList"
        :key="index"
      >
        <view class="record-item">
          <view class="record-left">
            <text class="record-time">{{ item.time }}</text>
            <text class="record-type">{{ item.type }}</text>
          </view>
          <view class="record-right">
            <text
              class="record-amount"
              :class="{
                positive: item.amount > 0,
                negative: item.amount < 0,
              }"
            >
              {{ item.amount > 0 ? "+" : "" }}{{ item.amount }}
            </text>
            <text class="record-balance"
              >结余：{{ item.balance.toFixed(2) }}</text
            >
          </view>
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="loading && page > 1" class="loading-more-wrapper">
        <text class="loading-more-text">加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMore && recordList.length > 0" class="no-more-wrapper">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </view>

    <!-- 时间选择器 -->
    <uni-popup ref="timePopup" type="bottom">
      <view class="time-picker-popup">
        <view class="popup-header">
          <text class="cancel-btn" @tap="cancelTimePicker">取消</text>
          <text class="title">选择时间</text>
          <text class="confirm-btn" @tap="confirmTimePicker">确定</text>
        </view>
        <picker-view
          class="picker-view"
          :value="pickerValue"
          @change="onPickerChange"
        >
          <picker-view-column>
            <view
              class="picker-item"
              v-for="(item, index) in yearMonthList"
              :key="index"
            >
              {{ item }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { coinFlowList } from "../../api/gift";

declare const uni: any;

interface FlowRecord {
  time: string;
  type: string;
  amount: number;
  balance: number;
}

interface ApiFlowRecord {
  id: number;
  send_user: number;
  rec_user: number | null;
  num: number;
  created_at: string;
  type: number;
  consume_type: number;
  remark: string | null;
  old_coin: number;
  new_coin: number;
  type_text: string;
}

const currentBalance = ref(0);
const selectedTime = ref("2025年7月");
const loading = ref(false);
const recordList = ref<FlowRecord[]>([]);
const timePopup = ref();
const pickerValue = ref([0]);
const consumeType = ref(7);
const uid = ref(0);

// 分页相关
const page = ref(1);
const pageSize = ref(20);
const hasMore = ref(true);
const isLoadingMore = ref(false);

// 动态生成近12个月列表
function getRecentMonths(count = 12) {
  const list: string[] = [];
  const now = new Date();
  for (let i = 0; i < count; i++) {
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    list.push(`${year}年${month.toString().padStart(2, "0")}月`);
    now.setMonth(now.getMonth() - 1);
  }
  return list;
}

const yearMonthList = ref(getRecentMonths(12));
selectedTime.value = yearMonthList.value[0];

// 获取年月字符串转为后端格式
function getMonthParam(str: string) {
  const m = str.match(/(\d{4})年(\d{1,2})月/);
  if (m) {
    return `${m[1]}-${m[2].padStart(2, "0")}`;
  }
  return "";
}

function convertFlowData(apiFlows: ApiFlowRecord[]): FlowRecord[] {
  return apiFlows.map((flow) => ({
    time: flow.created_at,
    type: flow.type_text,
    amount: flow.new_coin > flow.old_coin ? flow.num : -flow.num,
    balance: flow.new_coin || 0,
  }));
}

// 重置分页状态
const resetPagination = () => {
  page.value = 1;
  hasMore.value = true;
  recordList.value = [];
  isLoadingMore.value = false;
};

// 获取流水记录
const fetchRecords = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true;
      resetPagination();
    } else {
      isLoadingMore.value = true;
    }

    const month = getMonthParam(selectedTime.value);
    const res = await coinFlowList({
      type: consumeType.value,
      month,
      page: page.value,
      pageSize: pageSize.value,
    });

    if (res && res.result === 1) {
      currentBalance.value = parseFloat(res.data.balance);
      const newRecords = convertFlowData(res.data.flows);

      if (isLoadMore) {
        recordList.value = [...recordList.value, ...newRecords];
      } else {
        recordList.value = newRecords;
      }

      // 判断是否还有更多数据
      hasMore.value = newRecords.length === pageSize.value;
    } else {
      if (!isLoadMore) {
        currentBalance.value = 0;
        recordList.value = [];
      }
      uni.showToast({ title: res?.msg || "获取数据失败", icon: "none" });
    }
  } catch (error) {
    console.error("获取流水记录失败:", error);
    uni.showToast({ title: "获取数据失败", icon: "none" });
  } finally {
    loading.value = false;
    isLoadingMore.value = false;
  }
};

// 自动加载更多
const autoLoadMore = async () => {
  if (isLoadingMore.value || !hasMore.value || loading.value) return;

  page.value++;
  await fetchRecords(true);
};

// 触底监听 - 使用uni-app的onReachBottom
onReachBottom(() => {
  autoLoadMore();
});

const showTimePicker = () => {
  timePopup.value.open();
};

const cancelTimePicker = () => {
  timePopup.value.close();
};

const confirmTimePicker = () => {
  selectedTime.value = yearMonthList.value[pickerValue.value[0]];
  timePopup.value.close();
  fetchRecords(); // 选择后自动查询
};

const onPickerChange = (e: any) => {
  pickerValue.value = e.detail.value;
};

onLoad((options) => {
  if (options && options.type) {
    consumeType.value = Number(options.type);
  }
  if (options && options.uid) {
    uid.value = Number(options.uid);
  }
  fetchRecords();
});
</script>

<style lang="scss" scoped>
.flow-record-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.balance-header {
  background: #ffffff;
  padding: 30rpx 40rpx;
  display: flex;
  align-items: center;
  border-radius: 16rpx;
  margin: 24rpx 24rpx 0 24rpx;
  box-sizing: border-box;
}

.time-filter {
  padding: 24rpx 24rpx 0 24rpx;
  background: transparent;
  .filter-dropdown {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 0;
    .filter-text {
      font-size: 28rpx;
      color: #333333;
      margin-right: 8rpx;
    }
  }
}

.record-list {
  margin-top: 16rpx;
  padding: 0 24rpx;
  background: transparent;

  .loading-wrapper,
  .empty-wrapper {
    padding: 80rpx 0;
    text-align: center;
    .loading-text,
    .empty-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .record-item-card {
    background: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
    padding: 0;
  }

  .record-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24rpx 24rpx 16rpx 24rpx;
    border-bottom: none;
    .record-left {
      flex: 1;
      display: flex;
      flex-direction: column;
      .record-time {
        font-size: 26rpx;
        color: #999999;
        margin-bottom: 8rpx;
      }
      .record-type {
        font-size: 28rpx;
        color: #333333;
        line-height: 1.4;
      }
    }
    .record-right {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      min-width: 160rpx;
      .record-amount {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
        &.positive {
          color: #00a971;
        }
        &.negative {
          color: #ff4757;
        }
      }
      .record-balance {
        font-size: 26rpx;
        color: #999999;
      }
    }
  }

  .loading-more-wrapper {
    padding: 30rpx 0;
    text-align: center;
    .loading-more-text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .no-more-wrapper {
    padding: 30rpx 0;
    text-align: center;
    .no-more-text {
      font-size: 26rpx;
      color: #cccccc;
    }
  }
}

.time-picker-popup {
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 40rpx;
    border-bottom: 1rpx solid #f0f0f0;
    .cancel-btn,
    .confirm-btn {
      font-size: 28rpx;
      color: #00a971;
    }
    .title {
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }
  }
  .picker-view {
    height: 400rpx;
    padding: 0 40rpx;
    .picker-item {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 80rpx;
      font-size: 28rpx;
      color: #333333;
    }
  }
}
</style>
